from flask import Flask, render_template, send_from_directory, request, send_file, redirect, url_for, Blueprint
import os

from config import  local_base_dir

from flask_cors import CORS

# app = Flask(__name__)
# CORS(app)

# 文件夹路径，假设图片存放在 'static/images/' 目录下
app1 = Blueprint( __name__, __name__)


@app1.route('/')
def index():
    # 获取当前页数，默认为 0
    page = int(request.args.get('page', 0))
    per_page = 60  # 每页显示的图片数量

    # 获取选择的文件夹名称
    selected_folder = request.args.get('folder', None)

    # 获取 E:/work/ 下的所有文件夹名称
    base_dir = local_base_dir
    folders = [d for d in os.listdir(base_dir) if os.path.isdir(os.path.join(base_dir, d))]

    images = []
    if selected_folder:
        # 如果选择了某个文件夹，获取该文件夹中的图片
        folder_path = os.path.join(base_dir, selected_folder)
        for dirpath, dirnames, filenames in os.walk(folder_path):
            for filename in filenames:
                images.append(os.path.join(dirpath, filename))

    # 进行分页处理
    total_images = len(images)
    start = page * per_page
    end = start + per_page
    images_to_display = images[start:end]

    return render_template('index.html', images=images_to_display, folders=folders, total_images=total_images, page=page, selected_folder=selected_folder)
# @app1.route('/')
# def index():
#     folder_name = request.args.get('folder', None)
#       # 获取当前页数，默认为 0
#     page = int(request.args.get('page', 0))
#     per_page = 60  # 每页显示的图片数量
#     images = []
#     if folder_name :
#         # 如果提供了文件夹名称，则构建文件夹路径
#         target_folder = os.path.join("E:\work", folder_name)
#         if os.path.exists(target_folder) and os.path.isdir(target_folder):
#             for dirpath, dirnames, filenames in os.walk(target_folder):
#                 for filename in filenames:
#                     images.append(os.path.join(dirpath, filename))
#         else:
#             return f"文件夹 '{folder_name}' 不存在或不是一个有效的文件夹", 404
#     else:
#         # 使用 os.walk() 遍历文件夹及子文件夹
#         for dirpath, dirnames, filenames in os.walk("E:\work"):
#             for filename in filenames:
#                 # if filename.lower().endswith(('png', 'jpg', 'jpeg', 'gif')):
#                 # 将完整路径添加到图片列表中
#                 images.append(os.path.join(dirpath, filename))
#
#     # 进行分页处理
#     total_images = len(images)
#     start = page * per_page
#     end = start + per_page
#     images_to_display = images[start:end]
#
#     return render_template('index.html', images=images_to_display, total_images=total_images, page=page)

# 用于处理静态文件的路由
IMAGE_FOLDER = local_base_dir
@app1.route('/images/<path:filename>')
def send_image(filename):
    print(filename)
    if not filename.startswith('/'):
        filename = '/' + filename

    if IMAGE_FOLDER in {filename}:
        filename = filename.replace(IMAGE_FOLDER, '')
        print(filename)
    absolute_path = os.path.join(IMAGE_FOLDER, filename.lstrip('/'))
    print("Serving image from:", absolute_path)
    return send_file(filename)

@app1.route('/delete/<path:filename>', methods=['POST'])
def delete_image(filename):
    # 拼接完整路径
    file_path = os.path.join(IMAGE_FOLDER, filename)

    try:
        os.remove(file_path)  # 删除文件
    except Exception as e:
        print(f"Error deleting file {file_path}: {e}")
    return redirect(url_for('index'))  # 删除后重定向回首页

# if __name__ == '__main__':
#     app.run(host='0.0.0.0', debug=True)
